package com.project.yunshitong.utils;

import static android.content.ContentValues.TAG;
import static java.util.regex.Pattern.compile;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.Log;
import android.widget.TextView;

import org.apache.http.util.EncodingUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2018-05-25.
 */

public class Tools {

    public static String readFileSdcardFile(String fileName) throws IOException {
        String res = "";
        try {
            FileInputStream fin = new FileInputStream(fileName);

            int length = fin.available();

            byte[] buffer = new byte[length];
            fin.read(buffer);

            res = EncodingUtils.getString(buffer, "GB2312");

            fin.close();
//            Log.e(TAG, "readFileSdcardFile: res============" + res);
        } catch (Exception e) {
            e.printStackTrace();
//            Log.e(TAG, "readFileSdcardFile: e============" + e.getLocalizedMessage());
        }
        return res;
    }
    /**
     * 获取当前时间
     */
    public static String getNowTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(new Date());
        return dateString;
    }

    public static String getNowTime1() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = simpleDateFormat.format(System.currentTimeMillis());
        return dateString;
    }
    public static String getNowTime2() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = simpleDateFormat.format(System.currentTimeMillis());
        return dateString;
    }
    /*
     * 将时间戳转换为时间
     *
     * s就是时间戳
     */

    public static String stampToDate(long s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //如果它本来就是long类型的,则不用写这一步
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间戳转换为时间
     *
     * s就是时间戳
     */

    public static String stampToDateS(long s, String format) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        //如果它本来就是long类型的,则不用写这一步
        Date date = new Date(s);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间转换为时间戳
     */
    public static long dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
    }

    /*
     * 将时间转换为时间戳
     */
    public static long dateToStamp1(String s, String format) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        return ts;
    }

    /**
     * 点击某个textView，调起时间选择器，设置该时间选择器返回的时间给该textView
     *
     * @param tv textView
     */
    public static void getDateFromDatePickerDialog(Context context, TextView tv) {
        Calendar calendar = Calendar.getInstance();
        // 绑定监听器(How the parent is notified that the date is set.)
        new DatePickerDialog(context, AlertDialog.THEME_HOLO_LIGHT, (view, year, monthOfYear, dayOfMonth) -> {
            // 此处得到选择的时间，可以进行你想要的操作
            if ((monthOfYear + 1) < 10) {
                tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
            } else {
                tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            }
        }// 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    /**
     *      * 截断输出日志
     *      *
     *      * @param msg
     *      
     */
    public static void eLength(String tag, String msg) {

        /*if (tag == null || tag.length() == 0
                || msg == null || msg.length() == 0) {
            return;
        }
        int segmentSize = 2 * 1024;
        long length = msg.length();
//        if (length <= segmentSize) {// 长度小于等于限制直接打印
        */
        Log.e(tag, msg);
//        } else {
//            while (msg.length() > segmentSize) {// 循环分段打印日志
//                String logContent = msg.substring(0, segmentSize);
//                msg = msg.replace(logContent, "");
//                Log.e(tag, logContent);
//            }
//            Log.e(tag, msg);// 打印剩余日志
//        }
    }


    /**
     * 用来USB打印
     */
    public static JSONObject getPrintText(String info, int start, int size) {
        char[] text = info.toCharArray();
        String a = "";
        int length = 0;
        int index = start;
        boolean flag = false;//是否全部打印完成

        for (int i = start; i < text.length; i++) {
            length += getLength(String.valueOf(text[i]));
            a += String.valueOf(text[i]);
            index++;
            if (length >= size) {
                break;
            }
        }
        if (start == 0 && length < size) {
            for (int i = 0; i < size - length; i++) {
                a += " ";
            }
        }
        if (index >= text.length) {
            flag = true;
        }
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("value", a);
            jsonObject.put("length", index);
            jsonObject.put("flag", !flag);
        } catch (JSONException e) {
            e.printStackTrace();
            return new JSONObject();
        }
        //Log.e(TAG, "getPrintText: json=" + jsonObject);
        return jsonObject;
    }

    /**
     * 补充空格
     */
    public static String addSpace(String info, int size) {
        char[] text = info.toCharArray();
        String a = info;
        for (int i = 0; i < size - text.length; i++) {
            a += " ";
        }
        return a;
    }


    /**
     * 获取字符串占用的字符
     */
    private static int getLength(String msg) {
        char[] info = msg.toCharArray();
        String[] arr = {"*", ":", "-", "+", " ", ".", "|", ",", "×"};
        int num = 0;
//        Log.e(TAG, "getSpace: msg=" + msg);
        for (int i = 0; i < info.length; i++) {
            String txt = String.valueOf(info[i]);
//            Log.e(TAG, "getLength: txt====" + txt);
            Pattern p = compile("[0-9a-zA-Z]*");
            Pattern cn = compile("[\u4e00-\u9fa5]");
            if (isExpressionCharacter(info[i])) {

            } else if (p.matcher(txt).matches()) {//数字
                num += 1;
//                Log.e(TAG, "getSpace: 111111111");
            } else if (cn.matcher(txt).matches()) {//汉字
                num += 2;
//                Log.e(TAG, "getSpace: 333333333");
            } else if ("￥".equals(txt) || "（".equals(txt) || "）".equals(txt)) {
                num += 2;
//                Log.e(TAG, "getSpace: 444444444");
            } else {
                Set<String> set = new HashSet<>(Arrays.asList(arr));
                if (set.contains(txt)) {
                    num += 1;
//                    Log.e(TAG, "getSpace: 555555555");
                } else {
                    num += 1;
                }
            }
        }
        return num;
    }

    private static boolean isExpressionCharacter(char codePoint) {
        return !((codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)));
    }


    private static Bitmap bitmap;

    public static void returnBitMap(final String imgUrl) {
//        new MyAsyncTask().execute(imgUrl);
        /*InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        URL url = null;
        try {
            url = new URL(imgUrl);
//            Log.e(TAG, "returnBitMap: 847");
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            Log.e(TAG, "returnBitMap: 849");
            httpURLConnection.setRequestMethod("GET");
            Log.e(TAG, "returnBitMap: 851");
            httpURLConnection.setReadTimeout(2000);
            Log.e(TAG, "returnBitMap: 853");
            httpURLConnection.connect();
            Log.e(TAG, "returnBitMap: 855");
            if (httpURLConnection.getResponseCode() == 200) {
                Log.e(TAG, "returnBitMap: 857");
                //网络连接成功
                inputStream = httpURLConnection.getInputStream();
                outputStream = new ByteArrayOutputStream();
                byte buffer[] = new byte[1024 * 8];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, len);
                }
                byte[] bu = outputStream.toByteArray();
                Log.e(TAG, "returnBitMap: 111111111111111");
                Bitmap bitmap = BitmapFactory.decodeByteArray(bu, 0, bu.length);
                Log.e(TAG, "returnBitMap: 222222222222222");
                String filePath = getContext().getFilesDir().getPath();
                Log.e(TAG, "returnBitMap: 333333333333333");
                File file = new File(filePath, System.currentTimeMillis()+"");
                Log.e(TAG, "returnBitMap: 4444444444444");
                FileOutputStream out = null;
                Log.e(TAG, "returnBitMap: 555555555555555");
                try {
                    out = new FileOutputStream(file);
                    Log.e(TAG, "returnBitMap: 66666666666666");
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    Log.e(TAG, "returnBitMap: 777777777777777");
                    out.close();
                    Log.e(TAG, "saveBitmap: 图片保存成功" );
                } catch (IOException e) {
                    Log.e(TAG, "returnBitMap: error");
                    e.printStackTrace();
                }
                MyApplication.getComService().startTransferPicture();
                return bitmap;
            } else {
                Log.e(TAG, "网络连接失败----" + httpURLConnection.getResponseCode());
            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }*/


    }


    public static List<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
//            Log.e("error", "空目录");
            return null;
        }
        List<String> s = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            s.add(files[i].getAbsolutePath());
        }
        return s;
    }

    /**
     * 点击某个textView，调起时间选择器，设置该时间选择器返回的时间给该textView
     *
     * @param tv textView
     */
    public static void getDateFromDatePickerDialog(TextView tv, TimeCallback timeCallback) {
        Calendar calendar = Calendar.getInstance();
        // 绑定监听器(How the parent is notified that the date is set.)
        new DatePickerDialog(tv.getContext(), AlertDialog.THEME_HOLO_LIGHT, (view, year, monthOfYear, dayOfMonth) -> {
            // 此处得到选择的时间，可以进行你想要的操作
            if ((monthOfYear + 1) < 10) {
                if (dayOfMonth < 10) {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    timeCallback.time(year + "-0" + (monthOfYear + 1) + "-0" + dayOfMonth);
                } else {
                    tv.setText(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                    timeCallback.time(year + "-0" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            } else {
                if (dayOfMonth < 10) {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth);
                    timeCallback.time(year + "-" + (monthOfYear + 1) + "-0" + dayOfMonth);
                } else {
                    tv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    timeCallback.time(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                }
            }
        }// 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }

    public interface TimeCallback {
        void time(String time);
    }

}
